//
//  YBLookVideoVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/6.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBLookVideoVC.h"

#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/ZFIJKPlayerManager.h>
//#import <ZFPlayer/KSMediaPlayerManager.h>
#import <ZFPlayer/ZFAVPlayerManager.h>

#import "WuyouTangControlView.h"
#import "YBLookVideoCell.h"
#import "YBVipVC.h"
#import "YBRechargeVC.h"
#import "YBCommentToolBar.h"
#import "twEmojiView.h"
#import "YBTabBarController.h"
#import "YBUploadProgress.h"
#import "Loginbonus.h"  //每天第一次登录
#import "ZZCircleProgress.h"
#import "YBRedProfitVC.h"
#import "ZFCustomControlView.h"
#import "YBHomeRedObj.h"

#import "RegAlertView.h"

static NSString * const reuseIdentifier = @"collectionViewCell";

@interface YBLookVideoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,FirstLogDelegate>//homeRedDelegate
{
    int _lastPlayCellIndex;
    //rk_1-30
    BOOL _isDoubleClickRefresh;         //是否是双击刷新
    BOOL _isHome;
    BOOL _needCheckLimit;               //是否需要检查播放权限
    BOOL _isLoadingMore;                //列表是否正在加载总
    CGFloat lastContenOffset;
    BOOL _isFirstPlay;
    NSDictionary *_currentVideoDic;
    
    RKPlayerLeaveState _playerLeaveState;
    
    Loginbonus *firstLV;
    NSString *bonus_switch;
    NSString *bonus_day;
    NSArray  *bonus_list;
    NSString *dayCount;
    NSString *is_bonus;//是否签到
    
    ZZCircleProgress *progressView;
    
    UIButton *_normalBtn;
    NSDictionary *rulesDic;
}
@property(nonatomic,strong)NSString *hostID;    //视频主人ID
@property(nonatomic,copy)NSString *videoID;     //视频id
@property (nonatomic, strong) NSMutableArray *videoUrls;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) WuyouTangControlView *controlView;
@property (nonatomic, strong) ZFCustomControlView *fullControlView;

@property (nonatomic, strong) UIButton *backBtn;
@property(nonatomic,strong)YBLookVideoCell *playingCell;

@property(nonatomic,strong)YBCommentToolBar *commentTool;
@property(nonatomic,strong)YBUploadProgress *uploadView;

@end

@implementation YBLookVideoVC

/// 青少年模式切换,刷新首页
-(void)youngModeRefresh;{
    [self doubleClickRefreshForYou];
    _isDoubleClickRefresh = NO;
}
//rk_1-30
-(void)doubleClickRefreshForYou {
    if([_fromWhere isEqual:@"MsgTopPubVC"] ||[_fromWhere isEqual:@"NearbyVC"]){
        return;
    }
    
    //双击首页刷新推荐
    _isDoubleClickRefresh = YES;
    _needCheckLimit = YES;
    _pages = 1;
    [self.player stopCurrentPlayingCell];
    if (_videoList.count>0) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    [_videoList removeAllObjects];
    [MBProgressHUD showMessage:@""];
    [self pullData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    _lastPlayCellIndex = -1;
    _isDoubleClickRefresh = NO;
    _isLoadingMore = NO;
    lastContenOffset = 0;
    _isFirstPlay = NO;
    _currentVideoDic = @{};
    [self addNotifications];

    [self.view addSubview:self.collectionView];
    if (![PublicObj checkNull:minstr(_fromWhere)]) {
        [self.view addSubview:self.backBtn];
        [self.view addSubview:self.commentTool];
    }else{
        [self.view addSubview:self.uploadView];
    }
    
    self.videoUrls = [NSMutableArray array];
    
    if (!_videoList || _videoList.count <= 0) {
        //首页
        _isHome = YES;
        _needCheckLimit = YES;
        _pages = 1;
        self.videoList = [NSMutableArray array];
        [self pullData];
    }else {
        //其他页面push
        _isHome = NO;
        _needCheckLimit = NO;
        for (NSDictionary *subDic in _videoList) {
            NSString *videoUrl = minstr([subDic valueForKey:@"href"]);
            [_videoUrls addObject:[NSURL URLWithString:[PublicObj decrypt:videoUrl]]];
        }
        [self.player stopCurrentPlayingCell];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_pushPlayIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    
    /// playerManager
    ZFIJKPlayerManager *playerManager = [[ZFIJKPlayerManager alloc] init];
    NSString *ijkRef = [NSString stringWithFormat:@"Referer:%@\r\n",h5url];
    [playerManager.options setFormatOptionValue:ijkRef forKey:@"headers"];
    //KSMediaPlayer 设置referer需要在 KSMediaPlayerManager 的初始化里边
//    KSMediaPlayerManager *playerManager = [[KSMediaPlayerManager alloc]init];
//    [playerManager setRequestHeader:@{@"Referer":h5url}];
    
//    ZFAVPlayerManager*playerManager = [[ZFAVPlayerManager alloc] init];
//    NSDictionary *header = @{@"Referer":h5url};
//    NSDictionary *optiosDic = @{@"AVURLAssetHTTPHeaderFieldsKey" : header};
//    [playerManager setRequestHeader:optiosDic];
   
    
    /// player的tag值必须在cell里设置
    self.player = [ZFPlayerController playerWithScrollView:self.collectionView playerManager:playerManager containerViewTag:191107];
    self.player.controlView = self.controlView;
    self.player.assetURLs = self.videoUrls;
    self.player.shouldAutoPlay = YES;
    self.player.allowOrentitaionRotation = NO;
    self.player.WWANAutoPlay = YES;
    //不支持的方向
    self.player.disablePanMovingDirection = ZFPlayerDisablePanMovingDirectionVertical;
    //不支持的手势类型
    self.player.disableGestureTypes =  ZFPlayerDisableGestureTypesPinch;
    /// 1.0是消失100%时候
    self.player.playerDisapperaPercent = 1.0;
    
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
//        @strongify(self)
//            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
//            app.allowOrentitaionRotation = isFullScreen;
        @zf_strongify(self)
        if (isFullScreen) {
            self.player.disablePanMovingDirection = ZFPlayerDisablePanMovingDirectionNone;
        } else {
            self.player.disablePanMovingDirection = ZFPlayerDisablePanMovingDirectionAll;
        }
        self.player.controlView.hidden = YES;

    };
    self.player.orientationDidChanged = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        self.player.controlView.hidden = NO;
        if (isFullScreen) {
            self.player.controlView = self.fullControlView;
        } else {
            self.player.controlView = self.controlView;
        }
        [self orientationDidChangedResetTool];
    };

    self.player.presentationSizeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, CGSize size) {
        @strongify(self)
        if (size.width >= size.height) {
            self.player.currentPlayerManager.scalingMode = ZFPlayerScalingModeAspectFit;
        } else {
            self.player.currentPlayerManager.scalingMode = ZFPlayerScalingModeAspectFill;
        }
    };
    //功能
    self.player.playerPrepareToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
        NSLog(@"准备");
        @strongify(self)
        _isFirstPlay = YES;
        [self videoStart];
    };
    
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        NSLog(@"结束");
        @strongify(self)
        [self.player.currentPlayerManager replay];
        if (_isFirstPlay == YES) {
            _isFirstPlay = NO;
            [self videoEnd];
            [self addLookTimeForToday:[NSString stringWithFormat:@"%.0f",self.player.totalTime]];
        }
    };
    self.player.zf_playerDisappearingInScrollView = ^(NSIndexPath * _Nonnull indexPath, CGFloat playerDisapperaPercent) {
        @strongify(self);
        //这里代表将要切换视频
        if (playerDisapperaPercent == 1) {
            NSLog(@"100%%消失:%f",self.player.currentTime);
            _needCheckLimit = YES;
            if (_isFirstPlay == YES) {
                [self addLookTimeForToday:[NSString stringWithFormat:@"%.0f",self.player.currentTime]];
            }
            YBLookVideoCell *disCell = (YBLookVideoCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
            [disCell releaseObj:self.videoList[indexPath.row] isBackGround:NO];
            //上一个结束动画
            [disCell stopMusicAnimation:self.videoList[indexPath.row]];
        }
    };
    //停止的时候找出最合适的播放
    self.player.zf_scrollViewDidEndScrollingCallback = ^(NSIndexPath * _Nonnull indexPath) {
        @strongify(self)
        if (self.player.playingIndexPath) return;
        if (indexPath.row + 1 >= _videoList.count) {
            //加载下一页数据
            _pages += 1;
            [MBProgressHUD showMessage:@""];
            [self pullData];
        }else {
            [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
        }
    };
    [self showHomeVideoRed];
}
-(void)orientationDidChangedResetTool {
    // NSLog(@"rk===>[tool]:%d",_commentTool.isPrepareEditing);
    // NSLog(@"rk===>[tool]:%@",_commentTool);
    _commentTool.frame = CGRectMake(0,_window_height - 50-ShowDiff, _window_width, 50+ShowDiff);
    _commentTool.emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
}
-(void)showHomeVideoRed{
    if ([[Config getOwnID] intValue] <= 0) {
    }else{
        if([[common getVideoAwardSwitch] isEqual:@"1"]){
            [self requestWatchAward];
        }
    }
//    _isDoubleClickRefresh = NO;
//    [self doubleClickRefreshForYou];

}
-(void)hideHomeVideoRed{
    if(progressView){
        [progressView removeFromSuperview];
        progressView =nil;
    }
    [YBHomeRedObj redInstance].lookCount = 0;
    [YBHomeRedObj redInstance].startFloattime = 0.0f;
    [[YBHomeRedObj redInstance]timerEnd];
    _isDoubleClickRefresh = NO;
    [self doubleClickRefreshForYou];
        
}
-(void)tapsRedClick{
    YBRedProfitVC *vc = [[YBRedProfitVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];

}
#pragma mark ---红包开始
-(void)requestWatchAward{
    if(!progressView){
        progressView = [[ZZCircleProgress alloc] initWithFrame:CGRectMake(20,statusbarHeight+24+70, 60, 60) pathBackColor:[UIColor clearColor] pathFillColor:Pink_Cor startAngle:-90 strokeWidth:3];
        progressView.increaseFromLast = YES;//进度条动画是否从上次进度开始动画。默认为NO
        progressView.showPoint = NO;//是否显示默认小圆点。默认为YES
        progressView.showProgressText = NO;
        progressView.duration = 0.1;

        [self.view addSubview:progressView];
        UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapsRedClick)];
        [progressView addGestureRecognizer:taps];
        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"touid":[Config getOwnID],
                              };

        
        [WYNetworking postWithUrl:@"Video.getWatchVideoSeconds" Dic:dic Suc:^(int code, id info, NSString *msg) {
            if(code == 0){
                NSDictionary *infos = [info firstObject];
                if ([minstr([infos valueForKey:@"can_receive"]) isEqual:@"1"]) {
                    [[YBHomeRedObj redInstance]initWithTimer];
                    [[YBHomeRedObj redInstance]lookTimerStart];
                    [YBHomeRedObj redInstance].startEvent = ^(CGFloat currentTime) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            progressView.progress =currentTime;
                            NSLog(@"sdsadsadsd-----:%@",_videoID);
                        });

                    };
                }else{
                    [YBHomeRedObj redInstance].lookCount = 60;
                    progressView.progress = 1;
                }

            }
            } Fail:^(id fail) {
                
            }];

    }
    
    else{
        [YBHomeRedObj redInstance].startEvent = ^(CGFloat currentTime) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progressView.progress =currentTime;
                NSLog(@"sdsadsadsd--wwewwwww---:%@",_videoID);

            });

        };
    }
    
}
-(void)homeRedReloadTime:(CGFloat)currentTime{
    progressView.progress =currentTime;
}
-(void)timeGo{
    [[YBHomeRedObj redInstance]timerBegin];
}
#pragma mark ---红包结束


- (BOOL)shouldAutorotate {
    return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}
- (BOOL)prefersStatusBarHidden {
//    return [self.player isFullScreen];
    return NO;

}
//-(void)addAllFunctionBtn{
//    if(!_normalBtn){
//        _normalBtn = [UIButton buttonWithType:0];
//        _normalBtn.frame = CGRectMake(_window_width *0.15, _window_height *0.8, _window_width *0.7, 40);
//        _normalBtn.layer.cornerRadius = 20;
//        _normalBtn.layer.masksToBounds = YES;
//        [_normalBtn setBackgroundColor:Pink_Cor];
//        [_normalBtn setTitle:YZMsg(@"进入全功能模式") forState:0];
//        [_normalBtn setTitleColor:UIColor.whiteColor forState:0];
//        _normalBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//        [_normalBtn addTarget:self action:@selector(normalBtnClick) forControlEvents:UIControlEventTouchUpInside];
////        [self.view addSubview:_normalBtn];
////        _normalBtn.hidden = YES;
//
//    }
//}
//-(void)normalBtnClick{
//    [self showPrivateRule:rulesDic andIsFirst:NO];
//}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [self.controlView.zfVolumeView removeSystemVolumeView];
    _controlView.isDisappear = NO;
    if ([PublicObj checkNull:_fromWhere]) {
        [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"show_share_pop"];
    }
    [[YBDayTaskManager shareInstance]taskOfWatchVideoStart];
    
    [self.playingCell checkLiveOrAdState:_videoList[self.player.playingIndexPath.row]];
    [self ctrUpdateVideoInfo];
    
    //每天第一次登录
    if ([[Config getOwnID]intValue] > 0) {
        [self pullInternet];
    }
//    else{
//        [self getLoginThird];
//    }
    
//    [self addAllFunctionBtn];
//    if ([[Config getOwnID] intValue]>0 && [Config getTranslate]) {
//        _normalBtn.hidden = YES;
//    }

}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [self timerBegin];
    if ([[Config getOwnID] intValue] <= 0) {
    }else{
        if([[common getVideoAwardSwitch] isEqual:@"1"]){
            [[YBHomeRedObj redInstance]timerBegin];
            [self requestWatchAward];
        }
    }

//    if (_videoList.count<=0) {
//        return;
//    }

    //当前的开始动画
    [self.playingCell startMusicAnimation:_videoList[self.player.playingIndexPath.row]];
    
    //当从个人中心删除(或者游客登录)了视频时做个标记当返回推荐时候重新请求数据
    NSString *sign_del = [Config getSignOfDelVideo];
    if ([sign_del isEqual:@"1"]&&!_fromWhere) {
        [Config saveSignOfDelVideo:@"0"];
        [_videoList removeAllObjects];
        _needCheckLimit = YES;
        _pages = 1;
        [self pullData];
    }else if (!_isHome && !self.player.currentPlayerManager.isPlaying) {
        
        if (_firstPush) {
            _firstPush = NO;
            if (_pushPlayIndex + 1 >= _videoList.count && ![PublicObj checkNull:minstr(_sourceBaseUrl)]) {
                /// 加载下一页数据
                _pages += 1;
                [MBProgressHUD showMessage:@""];
                [self pullData];
            }else {
                [self startPlayerVideo];
            }
            return;
        }
        //NSLog(@"=====home:%lu",(unsigned long)self.player.currentPlayerManager.playState);
        ///播放离开回来继续播放，暂停离开回来还是暂停状态-start
        if (_playerLeaveState == RKLeaveState_Playing && self.player.currentPlayerManager.playState == 2) {
            [_controlView controlSingleTapped];
        }else if (_playerLeaveState == RKLeaveState_Pause){
            
        }else{
            [self startPlayerVideo];
        }
        ///播放离开回来继续播放，暂停离开回来还是暂停状态-end
        
    }
}
/**********************每天第一次登录-->>**********************/
-(void)pullInternet {
    [WYNetworking postWithUrl:@"User.Bonus" Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSArray *infos = info;
            bonus_switch = [NSString stringWithFormat:@"%@",[[infos lastObject] valueForKey:@"bonus_switch"]];
            bonus_day = [[infos lastObject] valueForKey:@"bonus_day"];
            bonus_list = [[infos lastObject] valueForKey:@"bonus_list"];
            dayCount = minstr([[infos lastObject] valueForKey:@"count_day"]);
            is_bonus = minstr([[infos lastObject] valueForKey:@"is_bonus"]);
            if ([bonus_switch isEqual:@"1"] &&
                [is_bonus isEqual:@"0"] &&
                [[Config getFirstBonus] isEqual:@"1"] &&
                ![PublicObj isUp] &&
                [YBYoungManager shareInstance].youngSwitch == 0) {
                
                [self firstLog];
                [Config saveFirstBonus:@"0"];
            }
        }
        } Fail:^(id fail) {
        }];
}
-(void)firstLog{
    firstLV = [[Loginbonus alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)AndNSArray:bonus_list AndDay:bonus_day andDayCount:dayCount andIsBonus:is_bonus];
    firstLV.delegate = self;
    [self.view addSubview:firstLV];
}

#pragma mark - 代理  动画结束释放空视图
-(void)removeView:(NSDictionary*)dic{
    [firstLV removeFromSuperview];
    firstLV = nil;
}
-(void)startPlayerVideo {
    @weakify(self)
    [self.collectionView zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath *indexPath) {
        @strongify(self)
        [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"show_share_pop"];
    [IQKeyboardManager sharedManager].enable = YES;
    _controlView.isDisappear = YES;
    NSLog(@"=====home:%lu",(unsigned long)self.player.currentPlayerManager.playState);
//    [self timerPause];
    [[YBHomeRedObj redInstance]timerPause];

    ///播放离开回来继续播放，暂停离开回来还是暂停状态-start
    if (self.player.currentPlayerManager.playState == 1) {
        _playerLeaveState = RKLeaveState_Playing;
        [_controlView controlSingleTapped];
    }else if (self.player.currentPlayerManager.playState == 2){
        _playerLeaveState = RKLeaveState_Pause;
    }else {
        [self.player stopCurrentPlayingCell];
    }
    ///播放离开回来继续播放，暂停离开回来还是暂停状态-end
    
    [self.controlView.zfVolumeView addSystemVolumeView];
    
    //停止动画
    [self.playingCell stopMusicAnimation:_videoList[self.player.playingIndexPath.row]];
    [[YBDayTaskManager shareInstance]taskOfWatchVideoEnd];
}

#pragma mark - private method
-(void)pullData{
    if (_isLoadingMore || [PublicObj checkNull:minstr(_sourceBaseUrl)]) {
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@&p=%@",_sourceBaseUrl,@(_pages)];
    if ([url containsString:@"Video.getRecommendVideos"]) {
        //是首页推荐 url 添加 isstart 并且当 _pages>1 时更改状态为0
        if (_pages>1) {
            [common saveIsStart:@"0"];
        }
        url = [url stringByAppendingFormat:@"&isstart=%@",[common getIsStart]];
    }
    YBWeakSelf;
    _isLoadingMore = YES;
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        _isLoadingMore = NO;
        if (code == 0) {
            
            NSArray *infoA = @[];
            if ([info isKindOfClass:[NSArray class]]) {
                infoA = [NSArray arrayWithArray:info];
            }
            if ([_fromWhere isEqual:@"YBTakeSameVideoVC"]) {
                //注意拍摄同款的视频列表在info[0]里边的videolist
                NSDictionary *infoDic = [info firstObject];
                infoA = [NSArray arrayWithArray:[infoDic valueForKey:@"videolist"]];
            }
            if ([_fromWhere isEqual:@"topicDetailsVC"]) {
                //注意标签的视频列表在info[0]里边的list
                NSDictionary *infoDic = [info firstObject];
                infoA = [NSArray arrayWithArray:[infoDic valueForKey:@"list"]];
            }
            if (_pages==1) {
                [_videoList removeAllObjects];
            }
            [_videoList addObjectsFromArray:infoA];
            if (_videoList.count<=0) {
                [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无推荐视频哦~") centerY:0.8];
            }else {
                [PublicView hiddenTextNoData:_collectionView];
            }
        
            [_videoUrls removeAllObjects];
            NSLog(@"beginTime-----:%@",[self getNowTimeTimestamp3]);
            for (NSDictionary *subDic in _videoList) {
                NSString *videoUrl = minstr([subDic valueForKey:@"href"]);
                [_videoUrls addObject:[NSURL URLWithString:[PublicObj decrypt:videoUrl]]];
                NSLog(@"当前完成-----:%@",[self getNowTimeTimestamp3]);

            }
            NSLog(@"endTime-----:%@",[self getNowTimeTimestamp3]);

            weakSelf.player.assetURLs = _videoUrls;
            [weakSelf.collectionView reloadData];
            //准备播放
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf startPlayerVideo];
                _isHome = NO;
            });
            if (_isDoubleClickRefresh == YES) {
                _isDoubleClickRefresh = NO;
                [MBProgressHUD showPop:YZMsg(@"刷新成功")];
            }
        }else{
            [MBProgressHUD hideHUD];
            _isLoadingMore = NO;
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
        _isLoadingMore = NO;
    }];
    
}
-(NSString *)getNowTimeTimestamp3{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSSSSS"];

    //现在时间,你可以输出来看下是什么格式

    NSDate *datenow = [NSDate date];

    //----------将nsdate按formatter格式转成nsstring

    NSString *currentTimeString = [formatter stringFromDate:datenow];

    return currentTimeString;
}
#pragma mark - 播放
/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    /*
    if (_lastPlayCellIndex != -1) {
        YBLookVideoCell *lastCell = (YBLookVideoCell*)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_lastPlayCellIndex inSection:0]];
        [lastCell releaseObj:_videoList[_lastPlayCellIndex]];
        //上一个结束动画
        [lastCell stopMusicAnimation:_videoList[_lastPlayCellIndex]];
        NSLog(@"playtime:%f",self.player.currentTime);
    }
    NSLog(@"last:%d==cure:%ld",_lastPlayCellIndex,(long)indexPath.row);
     */
    _lastPlayCellIndex = (int)indexPath.row;
    YBLookVideoCell *currentCell = (YBLookVideoCell*)[_collectionView cellForItemAtIndexPath:indexPath];
    [currentCell checkLiveOrAdState:_videoList[indexPath.row]];
    //当前的开始动画
    [currentCell startMusicAnimation:_videoList[indexPath.row]];
    
    _currentVideoDic = _videoList[indexPath.row];
    _videoID = minstr([_currentVideoDic valueForKey:@"id"]);
    NSDictionary *userInfo = [_currentVideoDic valueForKey:@"userinfo"];
    _hostID = minstr([userInfo valueForKey:@"id"]);
    
    if (_commentTool) {
        [_commentTool hiddenEmojiOrKeyBoard];
        _commentTool.player = self.player;
        _commentTool.videoid = _videoID;
        _commentTool.hostid = _hostID;
        [_commentTool resetToolState];
    }
    
    //[self.player playTheIndexPath:indexPath scrollToTop:scrollToTop];
    [self.player playTheIndexPath:indexPath scrollPosition:scrollToTop animated:NO];
    [self.controlView resetControlView];
    
    //player-contentMode
    CGFloat coverRatio = 1.78;
    if (![PublicObj checkNull:minstr([_currentVideoDic valueForKey:@"anyway"])]) {
        coverRatio = [minstr([_currentVideoDic valueForKey:@"anyway"]) floatValue];
    }
    UIViewContentMode imageMode;
    if (coverRatio > 1) {
        imageMode = UIViewContentModeScaleAspectFill;
    } else {
        imageMode = UIViewContentModeScaleAspectFit;
    }
    [self.controlView showCoverViewWithUrl:minstr([_currentVideoDic valueForKey:@"thumb"]) withImageMode:imageMode];
    [self.fullControlView showTitle:@"" coverURLString:minstr([_currentVideoDic valueForKey:@"thumb"]) fullScreenMode:ZFFullScreenModeLandscape];
    self.fullControlView.playDoc = _currentVideoDic;

    /*
    @weakify(self);
    [PublicObj getThumbSizeWithUrl:minstr([_currentVideoDic valueForKey:@"thumb"]) complete:^(CGFloat width, CGFloat height) {
        @strongify(self);
        UIViewContentMode imageMode;
        if (width >= height) {
            imageMode = UIViewContentModeScaleAspectFit;
        } else {
            imageMode = UIViewContentModeScaleAspectFill;
        }
        [self.controlView showCoverViewWithUrl:minstr([_currentVideoDic valueForKey:@"thumb"]) withImageMode:imageMode];
    }];
    */
    
    if (_needCheckLimit) {
        //获取播放权限等
        [self getVideo:indexPath scrollToTop:scrollToTop];
    }
}
-(void)getVideo:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    
    if (_controlView.currentVol>0) {
        [_controlView videoMuted:YES];
    }
    YBWeakSelf;
        [WYNetworking postWithUrl:@"Video.getVideo" Dic:@{@"videoid":_videoID,@"mobileid":[PublicObj getDeviceUUID]} Suc:^(int code, id info, NSString *msg) {
        
        if (code == 0) {
            _needCheckLimit = NO;
            _currentVideoDic = [info firstObject];
            if (_controlView.currentVol>0) {
                [_controlView videoMuted:NO];
            }
            
            //默默替换点赞、评论、分享等数据 (不要给currentCell.dataDic重新赋值,数据会闪动，体验不好)
            if ([_currentVideoDic isKindOfClass:[NSDictionary class]]&&_videoList.count>indexPath.row) {
                [_videoList replaceObjectAtIndex:indexPath.row withObject:_currentVideoDic];
            }
            
            YBLookVideoCell *currentCell = (YBLookVideoCell*)[_collectionView cellForItemAtIndexPath:indexPath];
            if ([[Config getOwnID] isEqual:_hostID] || [[_currentVideoDic valueForKey:@"isattent"] isEqual:@"1"]) {
                currentCell.followBtn.hidden = YES;
            }else{
                [currentCell.followBtn setImage:[UIImage imageNamed:@"home_follow"] forState:0];
                currentCell.followBtn.hidden = NO;
            }
            
            // 青少年模式受限
            if ([YBYoungManager shareInstance].youngBan == 1) {
                [_controlView showPlayBtn];
            }
            
        }
//        else if (code == 1001){
//            //需要登录
//            [PublicObj warnLogin];
//        }
//        else if (code == 1000){
//            //游客次数限制 弹窗模式,
//            [weakSelf limitPlayVideo:-1 andMsg:msg];
//        }
        else if(code == 1002){
            //需要开通Vip
            [weakSelf limitPlayVideo:1 andMsg:msg];
        }else if (code == 1003){
            //需要支付
            [weakSelf limitPlayVideo:2 andMsg:msg];
        }else {
            _needCheckLimit = YES;
            [_controlView showPlayBtn];
            [MBProgressHUD showPop:msg];
        }
    } Fail:nil];
}

-(void)limitPlayVideo:(int)limiteType andMsg:(NSString *)msg{
    _needCheckLimit = YES;
    [_controlView showPlayBtn];
    
    //limiteType  -1 游客 1：vip   2：pay
    YBWeakSelf;
    NSDictionary *contentDic = @{@"title":@"",@"msg":msg,@"left":YZMsg(@"取消"),@"right":(limiteType==1)?YZMsg(@"开通会员"):YZMsg(@"观看")};
    if (limiteType == -1) {
        contentDic = @{@"title":@"",@"msg":msg,@"left":@"",@"right":YZMsg(@"确认")};
    }
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            if ([[Config getOwnID] intValue]<=0) {
                [PublicObj warnLogin];
                return;
            }
            if ([YBYoungManager shareInstance].youngSwitch == 1) {
                [MBProgressHUD showError:YZMsg(@"青少年模式下不支持该功能")];
                return;
            }
            //确认按钮
            if (limiteType == 1) {
                //vip
                YBVipVC *vipVC = [[YBVipVC alloc]init];
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:vipVC animated:YES];
            }else if(limiteType == 2) {
                //付费观看
                [weakSelf goPay];
            }
        }
    }];
}
#pragma mark -
-(void)goPay {
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:@"Video.setVideoPay" Dic:@{@"videoid":_videoID} Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            [MBProgressHUD showPop:msg];
            _needCheckLimit = NO;
            [_controlView hiddenPlayBtn];
        }else if (code == 1004){
            //余额不足
            [weakSelf noMoney:msg];
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}
//余额不足提示
-(void)noMoney:(NSString *)msg {
    NSDictionary *contentDic = @{@"title":@"",@"msg":msg,@"left":YZMsg(@"取消"),@"right":YZMsg(@"去充值")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            //确认按钮
           YBRechargeVC *chargeVC = [[YBRechargeVC alloc]init];
           [[YBBaseAppDelegate sharedAppDelegate]pushViewController:chargeVC animated:YES];
        }
    }];
}
#pragma mark - UIScrollViewDelegate  列表播放必须实现
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidEndDecelerating];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
    if (!decelerate) {
        if (self.player.currentPlayIndex == 0 ) {
            [MBProgressHUD showPop:YZMsg(@"已经到顶了哦")];
        }
        if (self.player.currentPlayIndex+1 == _videoList.count) {
            [MBProgressHUD showPop:YZMsg(@"没有更多视频")];
        }
    }
}
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScroll];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewWillBeginDragging];
    lastContenOffset = scrollView.contentOffset.y;
//    [self.player stopCurrentPlayingCell];
}

#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _videoList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YBLookVideoCell *cell = (YBLookVideoCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.isForyou = _isForyou;
    cell.player = self.player;
    cell.fromWhere = _fromWhere;
    cell.dataDic = _videoList[indexPath.row];
    YBWeakSelf;
    cell.videoCellEvent = ^(NSString *eventType, NSDictionary *eventDic) {
        [weakSelf cellBlockBack:eventType andInfo:eventDic andIndex:indexPath];
    };
//    if ([YBYoungManager shareInstance].youngSwitch == 1) {
//        cell.giftBtn.hidden = YES;
//    }else{
//        cell.giftBtn.hidden = NO;
//    }
//
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.player.currentPlayIndex == indexPath.row) {
        return;
    }
    [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
}

#pragma mark - 功能
#pragma mark - cell block回调
-(void)cellBlockBack:(NSString *)eventType andInfo:(NSDictionary *)eventDic andIndex:(NSIndexPath *)indexPath{
    if ([eventType isEqual:@"视频-打赏"]) {
        //视频打赏处理
        [_controlView showGift:eventDic];
        
    }else if([eventType isEqual:@"视频-删除"]){
        //删除事件特殊处理
        if (!_fromWhere) {
            //推荐删除
            [_videoList removeObjectAtIndex:indexPath.row];
            /* //如果个人主页也要求删除后显示下一个(向上、向下滑),将if条件去掉else语句去掉执行下列if
             if (_fromWhere) {
                [Config saveSignOfDelVideo:@"1"];
                if (_videoList.count==0) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
             }
             */
            [_videoUrls removeAllObjects];
            for (NSDictionary *subDic in _videoList) {
                NSString *videoUrl = minstr([subDic valueForKey:@"href"]);
                [_videoUrls addObject:[NSURL URLWithString:[PublicObj decrypt:videoUrl]]];
            }
            [self.player stopCurrentPlayingCell];
            if (indexPath.row == _videoList.count) {
                //说明删除的是最后一个
                int toIndex = ((int)indexPath.row-1) < 0 ? 0 : ((int)indexPath.row-1);
                indexPath = [NSIndexPath indexPathForRow:toIndex inSection:0];
            }
            [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            self.player.assetURLs = _videoUrls;
            [self.collectionView reloadData];
            //准备播放
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self startPlayerVideo];
            });
        }else {
            //push页面删除
            [Config saveSignOfDelVideo:@"1"];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }else if ([eventType isEqual:@"视频-静音"]) {
        //静音事件特殊处理
        [self voiceRecordOrPlayEvent:eventDic];
    }else {
        //默默更新数据
        //视频-关注、视频-点赞、视频-评论
        NSMutableDictionary *m_dic = [NSMutableDictionary dictionaryWithDictionary:_videoList[indexPath.row]];
        [m_dic addEntriesFromDictionary:eventDic];
        [_videoList replaceObjectAtIndex:indexPath.row withObject:m_dic];
        _currentVideoDic = [NSDictionary dictionaryWithDictionary:m_dic];
    }
}
-(void)voiceRecordOrPlayEvent:(NSDictionary *)videoStateDic {
    int muteType = [minstr([videoStateDic valueForKey:@"mutedType"]) intValue];
    int playState = [minstr([videoStateDic valueForKey:@"playState"]) intValue];
//        [_controlView videoMuted:muteType];
    if (muteType == 0 && self.player.currentPlayerManager.isPlaying) {
        return;
    }
    if (playState == ZFPlayerPlayStatePlaying) {
        [_controlView controlSingleTapped];
    }
    //rk_解决语音评论导致声音问题
    if (muteType == 0) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    }
}

#pragma mark - 视频开始观看-结束观看
-(void)videoStart {
    if ([_hostID isEqual:[Config getOwnID]] || [[Config getOwnID] intValue] <= 0) {
        return;
    }
    NSString *random_str = [PublicObj stringToMD5:[NSString stringWithFormat:@"%@-%@-#2hgfk85cm23mk58vncsark",[Config getOwnID],_videoID]];
    [WYNetworking postWithUrl:@"Video.addView" Dic:@{@"videoid":_videoID,@"random_str":random_str} Suc:^(int code, id info, NSString *msg) {
        NSLog(@"addview-%d-%@-%@",code,info,msg);
    } Fail:nil];
}

-(void)videoEnd {
    if ([_hostID isEqual:[Config getOwnID]] || [[Config getOwnID] intValue] <= 0) {
        return;
    }
    NSString *random_str = [PublicObj stringToMD5:[NSString stringWithFormat:@"%@-%@-#2hgfk85cm23mk58vncsark",[Config getOwnID],_videoID]];
    [WYNetworking postWithUrl:@"Video.setConversion" Dic:@{@"videoid":_videoID,@"random_str":random_str} Suc:^(int code, id info, NSString *msg) {
        NSLog(@"setConversion-%d-%@-%@",code,info,msg);
    } Fail:nil];
}
#pragma mark - 增加观看时间
- (void)addLookTimeForToday:(NSString *)length{
    if ([length isEqual:@"0"] || [[Config getOwnID] intValue]<0 || [_hostID isEqual:[Config getOwnID]]) {
        return;
    }
    NSMutableDictionary *mudic = @{
                                   @"uid":[Config getOwnID],
                                   @"token":[Config getOwnToken],
                                   @"length":length
                                   }.mutableCopy;
    [mudic setObject:[PublicObj sortString:mudic] forKey:@"sign"];
    [WYNetworking postWithUrl:@"Agent.setViewLength" Dic:mudic Suc:^(int code, id info, NSString *msg) {
        NSLog(@"增加时间------------------%@",length);
    } Fail:^(id fail) {
        
    }];
}
#pragma mark - set/get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemWidth = self.view.frame.size.width;
        CGFloat itemHeight = self.view.frame.size.height;
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        layout.sectionInset = UIEdgeInsetsZero;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        if (self.scrollViewDirection == ZFPlayerScrollViewDirectionVertical) {
            layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        } else if (self.scrollViewDirection == ZFPlayerScrollViewDirectionHorizontal) {
            layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        }
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = Normal_Color;
        /// 横向滚动 这行代码必须写
        _collectionView.zf_scrollViewDirection = self.scrollViewDirection;
        [_collectionView registerClass:[YBLookVideoCell class] forCellWithReuseIdentifier:reuseIdentifier];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.scrollsToTop = NO;
        _collectionView.bounces = NO;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        /*
        /// 停止的时候找出最合适的播放
        @weakify(self)
        _collectionView.zf_scrollViewDidStopScrollCallback = ^(NSIndexPath * _Nonnull indexPath) {
            @strongify(self)
            if (self.player.playingIndexPath) return;
            if (indexPath.row + 1 >= _videoList.count) {
                /// 加载下一页数据
                _pages += 1;
                [MBProgressHUD showMessage:@""];
                [self pullData];
            }else {
                [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
            }
        };
        */
    }
    return _collectionView;
}

- (WuyouTangControlView *)controlView {
    if (!_controlView) {
        _controlView = [WuyouTangControlView new];
        @weakify(self);
        _controlView.ybContorEvent = ^(NSString *eventStr, ZFPlayerGestureControl *gesControl) {
            @strongify(self);
            [self contorEvent:eventStr andGes:gesControl];
        };
    }
    return _controlView;
}

-(void)contorEvent:(NSString *)eventStr andGes:(ZFPlayerGestureControl*)gesControl{
    if (_commentTool && _commentTool.isPrepareEditing) {
        [_commentTool hiddenEmojiOrKeyBoard];
        return;
    }
    if ([eventStr isEqual:@"控制-单击"]) {
        if (_needCheckLimit) {
            //获取播放权限等
            [self getVideo:self.player.playingIndexPath scrollToTop:NO];
        }else {
            [_controlView controlSingleTapped];
        }
    }
    if ([eventStr isEqual:@"控制-双击"]) {
//        if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//            return;
//        }

        if (_videoList.count<=0) {
            return;
        }
        if ([[Config getOwnID] intValue]<=0) {
            [PublicObj warnLogin];
            return;
        }
        NSString *isLike = minstr([_currentVideoDic valueForKey:@"islike"]);
        CGPoint center = [gesControl.doubleTap locationInView:self.controlView];
        [PublicObj doubleClickShowZan:self.controlView withCenter:center];
        //rk_2-23  双击对作品赞,双击不取消赞
        if ([isLike isEqual:@"0"]) {
            [self.playingCell clickLikeBtn];
        }
    }
    if ([eventStr isEqual:@"控制-主页"]) {
        [self.playingCell swipGesGoHome];
    }
    
    if ([eventStr isEqual:@"控制-观看左滑"] && self.leftEvent) {
        self.leftEvent();
    }
    
}

- (UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(0, 24+statusbarHeight, 40, 40);
        [_backBtn setImage:[UIImage imageNamed:@"pub_back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}
- (void)backClick:(UIButton *)sender {
    [self addLookTimeForToday:[NSString stringWithFormat:@"%.0f",self.player.currentTime]];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"yb_dsp_reset"]isEqual:@"1"]) {
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"yb_dsp_reset"];
        [PublicObj resetVC:[[YBTabBarController alloc]initWithAlert:NO]];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
- (YBCommentToolBar *)commentTool {
    YBWeakSelf;
    if (!_commentTool) {
        _commentTool = [[YBCommentToolBar alloc]initWithFrame:CGRectMake(0,_window_height - 50-ShowDiff, _window_width, 50+ShowDiff) andVCType:0 superView:self.view];
        _commentTool.backgroundColor = RGB_COLOR(@"#201C36", 0.2);
        _commentTool.comToolEvent = ^(NSString *eventType, NSDictionary *eventDic) {
            [weakSelf commentToolCallBack:eventType andEventDic:eventDic];
        };
    }
    return _commentTool;
}
-(void)commentToolCallBack:(NSString *)eventType andEventDic:(NSDictionary *)eventDic {
    if ([eventType isEqual:@"工具-游客"]) {
        [PublicObj warnLogin];
    }
    if ([eventType isEqual:@"工具-评论"]) {
        NSString *nums = minstr([eventDic valueForKey:@"comments"]);
        [self.playingCell updateCommentNums:nums];
    }
    if ([eventType isEqual:@"工具-录音"]) {
        [self voiceRecordOrPlayEvent:eventDic];
    }
}
- (YBLookVideoCell *)playingCell {
//    if (!_playingCell) {
        _playingCell = (YBLookVideoCell*)[_collectionView cellForItemAtIndexPath:self.player.playingIndexPath];
//    }
    return _playingCell;
}
#pragma mark - 通知
-(void)addNotifications {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadProNot:)name:@"uploadProNot" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadCoverNot:)name:@"uploadCoverNot" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youngModelTimeEnd:) name:ybYoungModelTimeEndEvent object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youngSiwtchOpen) name:ybYoungModelSwitchChage object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(timeGo) name:@"lookCountGo" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showHomeVideoRed) name:@"showHomeVideoRed" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideHomeVideoRed) name:@"hideHomeVideoRed" object:nil];

//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideBottomFunBtn) name:@"hideBottomFunBtn" object:nil];
}
//-(void)hideBottomFunBtn{
//    _normalBtn.hidden = YES;
//}
-(void)youngSiwtchOpen {
    if (firstLV) {
        [self removeView:@{}];
    }
}
-(void)youngModelTimeEnd:(NSNotification *)not {
    [_controlView showPlayBtn];
}
-(void)ctrUpdateVideoInfo {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"yb_update_video_on_other"]){
        NSDictionary *newDic = [[NSUserDefaults standardUserDefaults]objectForKey:@"yb_update_video_on_other"];
        if ([[_currentVideoDic valueForKey:@"id"] isEqual:[newDic valueForKey:@"id"]] && self.playingCell) {
            [self.playingCell noticeUpdateUI:newDic];
            [_videoList replaceObjectAtIndex:self.player.currentPlayIndex withObject:newDic];
        }
    }
}
#pragma mark - 前后台
-(void)onAppDidEnterBackground {
//    [self timerPause];
    [[YBHomeRedObj redInstance]timerPause];

    //停止动画
    [self.playingCell stopMusicAnimation:_videoList[self.player.playingIndexPath.row]];
    [self.playingCell releaseObj:self.videoList[self.player.playingIndexPath.row] isBackGround:YES];
    [self uploadViewBackgroundOrForegroundCtr:YES];
}
-(void)onAppWillEnterForeground {
//    [self timerBegin];
    [[YBHomeRedObj redInstance]timerBegin];

    //当前的开始动画
    [self.playingCell startMusicAnimation:_videoList[self.player.playingIndexPath.row]];
    [self.playingCell checkLiveOrAdState:_videoList[self.player.playingIndexPath.row]];
    [self uploadViewBackgroundOrForegroundCtr:NO];
}

- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.origin.y;
    if (_commentTool) {
        _commentTool.isPrepareEditing = YES;
        _commentTool.faceBtn.selected = NO;
        _commentTool.frame = CGRectMake(0, height - 50, _window_width, 50);
        _commentTool.emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
    }
}
- (void)keyboardWillHide:(NSNotification *)aNotification {
    //键盘消失一定要判断 faceBtn.selected 状态
    if (_commentTool && _commentTool.faceBtn.selected == NO) {
        [_commentTool hiddenEmojiOrKeyBoard];
        _commentTool.isPrepareEditing = NO;
    }
}
-(void)uploadProNot:(NSNotification *)aNotification {
    CGFloat notiPro = [aNotification.object floatValue];
    self.uploadProgress = notiPro;
}
-(void)uploadCoverNot:(NSNotification *)aNotification {
    UIImage *notiCover = (UIImage *)aNotification.object;
    self.uploadCover = notiCover;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark - 转屏和状态栏
//- (BOOL)shouldAutorotate {
//    return NO;
//}
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}
//- (BOOL)prefersStatusBarHidden {
//    return NO;
//}
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

#pragma mark - 视频上传进度 s
- (YBUploadProgress *)uploadView {
    if (!_uploadView) {
        CGFloat _www = _window_width*0.2;
        CGFloat _hhh = _www*4/3;
        _uploadView = [[YBUploadProgress alloc]initWithFrame:CGRectMake(10, 74+statusbarHeight, _www, _hhh)];
        _uploadView.hidden = YES;
    }
    return _uploadView;;
}
- (void)setUploadProgress:(CGFloat)uploadProgress{
    dispatch_async(dispatch_get_main_queue(), ^{
        _uploadProgress = uploadProgress;
        UIApplicationState state = [UIApplication sharedApplication].applicationState;
        if (state == UIApplicationStateActive){
            _uploadView.progress = _uploadProgress;
            if (_uploadProgress >= 1) {
                _uploadView.hidden = YES;
                if (_videoList.count<=0) {
                    [self doubleClickRefreshForYou];
                    _isDoubleClickRefresh = NO;
                }
            }
        }
    });
}
- (void)setUploadCover:(UIImage *)uploadCover{
    dispatch_async(dispatch_get_main_queue(), ^{
        _uploadCover = uploadCover;
        UIApplicationState state = [UIApplication sharedApplication].applicationState;
        if (state == UIApplicationStateActive){
            _uploadView.hidden = NO;
            _uploadView.proImg = _uploadCover;
        }
    });
}
-(void)uploadViewBackgroundOrForegroundCtr:(BOOL)isBack {
   
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (0 < app.allUploadPro && app.allUploadPro < 1 && isBack == NO) {
        _uploadView.hidden = NO;
    }else{
        _uploadView.hidden = YES;
        if (_videoList.count<=0) {
            [self doubleClickRefreshForYou];
            _isDoubleClickRefresh = NO;
        }
    }
}
#pragma mark - 视频上传进度 e


- (ZFCustomControlView *)fullControlView {
    if (!_fullControlView) {
        YBWeakSelf;
        _fullControlView = [[ZFCustomControlView alloc] init];
        _fullControlView.player = self.player;
        _fullControlView.bottomEvent = ^(NSString *str) {
            if([str isEqual:@"关闭评论"]){
                [[NSNotificationCenter defaultCenter]postNotificationName:UIKeyboardWillHideNotification object:nil];
            }
        };
    }
    return _fullControlView;
}
@end
